//
//  ChangeCashViewController.m
//  OurWallet
//
//  Created by 小肥羊 on 16/1/4.
//  Copyright © 2016年 小肥羊. All rights reserved.
//

#import "ChangeCashViewController.h"
#import "XFYSelectScrollView.h"
#import "SelectDateView.h"
#import "ActionView.h"
#import "WalletRecordCell.h"

static NSString *WalletRecordCellIdentifier = @"WalletRecordCell";

@interface ChangeCashViewController () <SelectDateDelegate, XFYSelectScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UITextField *changeMoneyText;
@property (weak, nonatomic) IBOutlet XFYSelectScrollView *moneyForSelectView;
@property (weak, nonatomic) IBOutlet UIButton *changeDateButton;
@property (weak, nonatomic) IBOutlet UITextField *remarkText;
@property (weak, nonatomic) IBOutlet UITableView *recordTableView;
@property (weak, nonatomic) IBOutlet UIButton *imageButton;

@property (nonatomic, strong) SelectDateView *selectDateView;   /**< 选择时间视图 */
@property (nonatomic, strong) NSString *moneyFor;               /**< 消费源 */
@property (nonatomic, strong) NSDate *selectDate;               /**< 时间 */
@property (nonatomic, strong) NSData *imageData;                /**< 图片 */
@property (nonatomic, strong) NSArray *recordArray;             /**< 记录 */
@property (nonatomic, getter=isConsume) BOOL consume;

@end

@implementation ChangeCashViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.recordArray = [[NSArray alloc] init];
    __weak typeof(self) _WeakSelf = self;
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"ChangeRecord"];
    [bquery whereKey:@"fromUserId" equalTo:USERINFO.objectId];
    [bquery whereKey:@"useFrom" equalTo:Macro_MoneyFromWallet];
    [bquery orderByDescending:@"recordTime"];
    bquery.limit = 10;
    [bquery calcInBackgroundWithBlock:^(NSArray *array,NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            _WeakSelf.recordArray = array;
            [_WeakSelf.recordTableView reloadData];
        });
    }];
    [self.changeMoneyText setPlaceholder:[NSString stringWithFormat:@"总金额:%@",[USERINFO.cash stringValue]]];
    self.moneyForSelectView.delegate = self;
    self.selectDate = [NSDate date];
    [self.changeDateButton.layer setCornerRadius:kNomalRadius];
    [self.changeDateButton.layer setBorderWidth:0.8];
    [self.changeDateButton.layer setBorderColor:KTableViewSeparatorColor.CGColor];
    self.recordTableView.delegate = self;
    self.recordTableView.dataSource = self;
    [self.recordTableView registerNib:[UINib nibWithNibName:WalletRecordCellIdentifier bundle:nil] forCellReuseIdentifier:WalletRecordCellIdentifier];
    self.consume = YES;
}

#pragma mark - 惰性初始化
- (SelectDateView *)selectDateView
{
    if (!_selectDateView) {
        _selectDateView = [[SelectDateView alloc] initWithDelegate:self];
    }
    return _selectDateView;
}

#pragma mark - 设置属性
- (void)setConsume:(BOOL)consume
{
    _consume = consume;
    if (_consume) {
        [self setTitle:@"消费"];
        [self.typeLabel setText:@"消费金额:"];
        self.moneyForSelectView.contents = [[NSMutableArray alloc] initWithArray:Macro_MoneyForDraw];
        self.moneyFor = Macro_MoneyForDraw[0];
    } else {
        [self setTitle:@"入帐"];
        [self.typeLabel setText:@"入帐金额:"];
        self.moneyForSelectView.contents = [[NSMutableArray alloc] initWithArray:Macro_MoneyForSave];
        self.moneyFor = Macro_MoneyForDraw[0];
    }
}
- (void)setSelectDate:(NSDate *)selectDate
{
    _selectDate = selectDate;
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:_selectDate];
    [self.changeDateButton setTitle:locationString forState:UIControlStateNormal];
}

#pragma mark - 操作
- (IBAction)clickBackground:(id)sender {
    [self.view endEditing:YES];
}
- (IBAction)changeType:(UISwitch *)sender {
    self.consume = sender.isOn;
}
- (IBAction)changeDate:(id)sender {
    [self.view endEditing:YES];
    [ActionView showView:self.selectDateView direction:PopViewDirectionStyleCenter];
}
- (IBAction)addImage:(id)sender {
    UIActionSheet *sheet;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"设置照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍摄新相片",@"从照片库选择", nil];
    }
    else
    {
        sheet = [[UIActionSheet alloc] initWithTitle:@"设置照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从照片库选择", nil];
    }
    [sheet showInView:self.view];
}

- (IBAction)confirm:(id)sender {
    if ([self.changeMoneyText.text isEqualToString:@""]) {
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你还没输入金额" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [alter show];
        return;
    }
    [self addProgressHud];
    __weak typeof(self) _WeakSelf = self;
    if (self.imageData) {
        BmobFile *bmobFile = [[BmobFile alloc] initWithFileName:@"recordImage.jpg"  withFileData:self.imageData];
        [bmobFile saveInBackground:^(BOOL isSuccessful, NSError *error) {
            [_WeakSelf removeProgressHud];
            if (isSuccessful) {
                [_WeakSelf upRecordWithBmobFile:bmobFile];
            } else {
                [MBProgressHUD showErrorWithText:error.userInfo[@"error"]];
            }
        } withProgressBlock:^(float progress) {
            NSLog(@"%f",progress);
        }];
    } else {
        [_WeakSelf upRecordWithBmobFile:nil];
    }
}

- (void)upRecordWithBmobFile:(BmobFile *)image
{
    NSInteger changeMoney = [self.changeMoneyText.text integerValue];
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
    __weak typeof(self) _WeakSelf = self;
    [bquery getObjectInBackgroundWithId:USERINFO.objectId block:^(BmobObject *object,NSError *error){
        if (!error) {
            if (object) {
                BmobObject *user = [BmobObject objectWithoutDatatWithClassName:object.className objectId:object.objectId];
                if (_WeakSelf.isConsume) {
                    [user decrementKey:@"cash" byAmount:changeMoney];
                } else {
                    [user incrementKey:@"cash" byAmount:changeMoney];
                }
                [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    [_WeakSelf removeProgressHud];
                    if (isSuccessful) {
                        [MBProgressHUD showSuccessWithText:@"更新成功"];
                        [WalletNetwork changeRecordWithUseFor:_WeakSelf.moneyFor UseFrom:Macro_MoneyFromWallet Money:changeMoney Consume:_WeakSelf.consume Remark:_WeakSelf.remarkText.text RecordTime:_WeakSelf.selectDate RecordImage:image];
                        [_WeakSelf.navigationController popViewControllerAnimated:YES];
                    } else {
                        [MBProgressHUD showErrorWithText:error.userInfo[@"error"]];
                    }
                }];
            }
        } else {
            [_WeakSelf removeProgressHud];
            [MBProgressHUD showErrorWithText:@"更新失败"];
        }
    }];
}

#pragma mark 键盘代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 列表显示代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.recordArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WalletRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:WalletRecordCellIdentifier];
    BmobObject *data = self.recordArray[indexPath.row];
    NSDictionary *recordDtate = [data objectForKey:@"recordTime"];
    [cell.moneyFrom setText:[data objectForKey:@"useFor"]];
    [cell.remarks setText:[data objectForKey:@"remark"]];
    [cell.recordDate setText:[recordDtate objectForKey:@"iso"]];
    [cell moneyText:[[data objectForKey:@"money"] stringValue] Consume:[[data objectForKey:@"consume"] boolValue]];
    if ([data objectForKey:@"recordImage"]) {
        BmobFile *file = (BmobFile *)[data objectForKey:@"recordImage"];
        [cell.recordImage sd_setImageWithURL:[WalletNetwork imageURLWithString:file.url]];
    }
    return cell;
}

#pragma mark - XFYSelectScrollView代理
- (void)operation:(XFYSelectScrollView *)selectView Button:(UIButton *)button AtIndex:(NSInteger)index
{
    [self.view endEditing:YES];
    self.moneyFor = button.titleLabel.text;
}

#pragma mark - 时间选择代理
- (void)selectDate:(SelectDateView *)picker
{
    self.selectDate = picker.datePicker.date;
    [ActionView closeView:picker];
}
- (void)cancelSelect:(SelectDateView *)picker
{
    [ActionView closeView:picker];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSUInteger sourceType = 0;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
            case 0: // 拍摄新相片
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 1: // 从照片库选择
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 2: // 取消
                return;
        }
    }
    else {
        if (buttonIndex == 0) {
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
        else {  // 取消
            return;
        }
    }
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:NO  completion:nil];
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self.imageButton setImage:image forState:UIControlStateNormal];
    self.imageData = UIImageJPEGRepresentation(image, 0.2);
    [picker dismissViewControllerAnimated:YES completion:^{
        [self.imageButton setImage:image forState:UIControlStateNormal];
    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
